from loguru import logger
from tinkoff.invest import CandleInterval, Client
from tinkoff.invest.utils import now
from tinkoff.invest.utils import candle_interval_to_timedelta
import os
import sys

# logger.add(sys.stdout, format="{time} {level} {message}", level="DEBUG")

token = os.getenv("token_name")

def get_5_day_candles(token):
    logger.info("Запуск функции get_5_day_candles")
    with Client(token) as client:
        figi="BBG004731032"
        _to=now()
        count_candles=5
        interval=CandleInterval.CANDLE_INTERVAL_DAY

        logger.debug(f"Запрос свечей для {figi} с интервалом {interval}")
        try:
            candles = client.market_data.get_candles(
                figi=figi,
                from_=_to - candle_interval_to_timedelta(interval) * (count_candles),
                to=_to,
                interval=interval
            )
            logger.info(f"Получено {len(candles.candles)} свечей")
        except Exception as e:
            logger.error(f"Ошибка при получении данных: {e}")
            raise e

        return candles
    
from tinkoff.invest.exceptions import RequestError

def get_all_figi(token):
        """Получает список всех figi с помощью Tinkoff Invest API и сохраняет их в бд."""
        figi_list = []
        with Client(token) as client:
            try:
                instruments = client.instruments.shares()
                for instrument in instruments.instruments:
                    figi_list.append([instrument.figi, instrument.name, instrument.ticker])
            except RequestError as e:
                print(f"Ошибка при получении данных: {e}")
        return figi_list
# x = get_all_figi(token)
# for i in x:
#     print(i)
y = get_5_day_candles(token)
print(y)

